package net.cmbt.okframe.okbottomtab;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class BitmapUtils
{

	/**
	 * set image src
	 * 
	 * @param imageView
	 * @param imagePath
	 */
	private void setImageSrc(ImageView imageView, String imagePath)
	{
		BitmapFactory.Options option = new BitmapFactory.Options();
		option.inSampleSize = getImageScale(imagePath);
		Bitmap bm = BitmapFactory.decodeFile(imagePath, option);
		imageView.setImageBitmap(bm);
	}

	private static int IMAGE_MAX_WIDTH = 480;
	private static int IMAGE_MAX_HEIGHT = 960;

	/**
	 * scale image to fixed height and weight
	 * 
	 * @param imagePath
	 * @return
	 */
	private static int getImageScale(String imagePath)
	{
		BitmapFactory.Options option = new BitmapFactory.Options();
		// set inJustDecodeBounds to true, allowing the caller to query the
		// bitmap info without having to allocate the
		// memory for its pixels.
		// 表示仅读取图片文件信息而不为图片分配内存。
		option.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(imagePath, option);

		int scale = 1;
		while (option.outWidth / scale >= IMAGE_MAX_WIDTH || option.outHeight / scale >= IMAGE_MAX_HEIGHT)
		{
			scale *= 2;
		}
		return scale;
	}

	public static String NICKIMAGE_DIR = Environment.getExternalStorageDirectory() + "/" + "MS_OKFRAME" + "/";

	public static Bitmap returnBitMap(String url, String imgName)
	{

		// TODO
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try
		{
			myFileUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			File file = new File("");
			if (!file.exists())
			{
				file.mkdirs();
			}
			// TODO
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (Exception e)
		{
			e.printStackTrace();
			// System.out.println("找不到文件");
		}
		return bitmap;
	}

	/**
	 * 
	 * @param bm
	 * @param name
	 * @return
	 * 
	 *         返回 1：成功 2 : 失败
	 */
	public static int saveFile(Bitmap bm, String name)
	{
		File dirFile = new File(NICKIMAGE_DIR);
		if (!dirFile.exists())
		{
			dirFile.mkdirs();
		}

		try
		{
			File myCaptureFile = new File(NICKIMAGE_DIR, name);
			BufferedOutputStream bos;
			bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
			bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();

			return 1;
		} catch (Exception e)
		{
			e.printStackTrace();
			return 2;
		}

	}
}
